package vaadin.lab3;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class Lab extends Application implements
        LongRunningOperation.FinishedListener {

    private HorizontalLayout mainLayout = new HorizontalLayout();
    private boolean isRunning = false;
    private Label statusLabel;
    private ProgressIndicator progressIndicator;

    @Override
    public void init() {
        mainLayout.setSpacing(true);
        mainLayout.setMargin(true);
        Window mainWindow = new Window("Lab", mainLayout);
        setMainWindow(mainWindow);

        progressIndicator = new ProgressIndicator();
        progressIndicator.setPollingInterval(200);
        progressIndicator.setIndeterminate(true);
        progressIndicator.setVisible(false);

        statusLabel = new Label("Not started");
        statusLabel.setSizeUndefined();
        Button button = new Button("Start", new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                if (!isRunning) {
                    isRunning = true;
                    statusLabel.setValue("Running");
                    LongRunningOperation longRunningOperation = new LongRunningOperation();
                    longRunningOperation.addListener(Lab.this);
                    progressIndicator.setVisible(true);
                    longRunningOperation.start();
                }
            }
        });
        button.setWidth("100px");

        mainLayout.addComponent(button);
        mainLayout.addComponent(progressIndicator);
        mainLayout.addComponent(statusLabel);
        mainLayout.setExpandRatio(statusLabel, 1.0f);
    }

    @Override
    public void finished(vaadin.lab3.LongRunningOperation.FinishEvent event) {
        synchronized (this) {
            statusLabel.setValue("Finished");
            isRunning = false;
            progressIndicator.setVisible(false);
        }
    }


}
